package com.hyxt.DTO.process;

import com.hyxt.DTO.CommonMessage;
import com.hyxt.DTO.CommonMessageHeader;
import com.hyxt.DTO.T809_MessageHeader;
import com.hyxt.superviseservice.CommonMessageBody;
import com.hyxt.superviseservice.IMessageBody;
import com.hyxt.superviseservice.messageBody.T809_0x1203;
import com.hyxt.utils.BytesUtil;
import com.hyxt.utils.T809_Process;
import com.hyxt.utils.T809_Util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Project: CNPC_VMS
 * @Title: T809_0x1203_Process
 * @Description:
 * @author: denghl
 * @date: 2014年4月24日 下午5:11:36
 * @company: Beijing Huayou Information andCommunication Technology Co.,Ltd
 * @Copyright: Copyright (c) 2014
 * @version V2.0
 */
public class T809_0x1203_Process<B extends IMessageBody> extends T809_Process<B> {
	private static Log log = LogFactory.getLog(T809_0x1203_Process.class);

	@Override
	protected CommonMessageBody getBody(CommonMessageHeader header, byte[] data) {
		// TODO Auto-generated method stub
		T809_0x1203 body = new T809_0x1203();
		// 车牌号
		byte[] VEHICLE_NO = BytesUtil.cutBytes(0, 21, data);
		// 车牌颜色
		byte VEHICLE_COLOR = BytesUtil.getByte(21, data);
		// 数据类型
		byte[] DATA_TYPE = BytesUtil.getWord(22, data);
		// 数据长度
		byte[] DATA_LENGTH = BytesUtil.cutBytes(24, 4, data);
		// 卫星定位数量
		int gnss_CNT = BytesUtil.getByte(28, data);
		List excryptList = new ArrayList();
		List dateList = new ArrayList();
		List timeList = new ArrayList();
		List lonList = new ArrayList();
		List latList = new ArrayList();
		List vec1List = new ArrayList();
		List vec2List = new ArrayList();
		List vec3List = new ArrayList();
		List directionList = new ArrayList();
		List altitudeList = new ArrayList();
		List stateList = new ArrayList();
		List alarmList = new ArrayList();

		for (int i = 0; i < gnss_CNT; i++) {
			// 数据加密标识
			byte excrypt = BytesUtil.getByte(29 + i * 36, data);
			excryptList.add(excryptList);
			// 年月日
			byte[] date = BytesUtil.cutBytes(30 + i * 36, 4, data);
			dateList.add(date);
			// 时间
			byte[] time = BytesUtil.cutBytes(34 + i * 36, 3, data);
			timeList.add(time);
			// 经度
			byte[] lon = BytesUtil.cutBytes(37 + i * 36, 4, data);
			lonList.add(lon);
			// 纬度
			byte[] lat = BytesUtil.cutBytes(41 + i * 36, 4, data);
			latList.add(lat);
			// 速度
			byte[] vec1 = BytesUtil.getWord(45 + i * 36, data);
			vec1List.add(vec1);
			// 行驶记录速度
			byte[] vec2 = BytesUtil.getWord(47 + i * 36, data);
			vec2List.add(vec2);
			// 车辆当前里程数
			byte[] vec3 = BytesUtil.cutBytes(49 + i * 36, 4, data);
			vec3List.add(vec3);
			// 方向
			byte[] direction = BytesUtil.getWord(53 + i * 36, data);
			directionList.add(direction);
			// 海拔高度
			byte[] altitude = BytesUtil.getWord(55 + i * 36, data);
			altitudeList.add(altitude);
			// 车辆状态
			byte[] state = BytesUtil.cutBytes(57 + i * 36, 4, data);
			stateList.add(state);
			// 报警状态
			byte[] alarm = BytesUtil.cutBytes(61 + i * 36, 4, data);
			alarmList.add(alarm);
		}
		try {
			body.setVEHICLE_NO(new String(VEHICLE_NO, "GBK"));
		} catch (UnsupportedEncodingException e) {
			log.warn("", e);
		}
		// 设置属性
		body.setVEHICLE_COLOR(VEHICLE_COLOR);
		body.setDATA_TYPE(BytesUtil.parseBytesToShort(DATA_TYPE));
		body.setDATA_LENGTH(BytesUtil.parseBytesToInt(DATA_LENGTH));
		body.setGnss_CNT(gnss_CNT);
		body.setExcrypt(excryptList);
		body.setDate(dateList);
		// 设置时间
		body.setTime(timeList);
		body.setLon(lonList);
		body.setLat(latList);
		body.setVec1(vec1List);
		body.setVec2(vec2List);
		// 设置里程数
		body.setVec3(vec3List);
		body.setDirection(directionList);
		body.setAltitude(altitudeList);
		body.setState(stateList);
		body.setAlarm(alarmList);
		return body;
	}

	/**
	 * @Description:数据打包类
	 */
	@Override
	protected byte[] packData(CommonMessage<B> message) {
		T809_0x1203 body1203 = (T809_0x1203) message.getMessageBody();
		List<String[]> gps = body1203.getGPSInfo();
		String[] indexData = gps.get(0);
		body1203.setVEHICLE_NO(indexData[0]);
		body1203.setVEHICLE_COLOR(BytesUtil.parseIntToByte(Integer.parseInt(indexData[1])));
		// 此数据体数据长度为27,数据长度(包括头标识、数据头、数据体、CRC校验码和尾标识)
		// 总共68字节
		byte[] head = new byte[22];
		byte[] datalength = BytesUtil.int2bytes4(55 + gps.size() * 36);
		datalength = BytesUtil.getBigDWord(0, datalength);
		System.arraycopy(datalength, 0, head, 0, datalength.length);

		// 报文序列号*占4字节
		byte[] MSG_SN = BytesUtil.int2bytes4(((T809_MessageHeader) message.getMessageHeader()).getSn());
		head[4] = MSG_SN[3];
		head[5] = MSG_SN[2];
		head[6] = MSG_SN[1];
		head[7] = MSG_SN[0];
		// 业务数据类型,占2字节
		// byte[] MSG_ID =
		// BytesUtil.int2bytes2(Integer.parseInt((((T809_MessageHeader)message.getMessageHeader()).getMessageID()).toString()));
		head[8] = (byte) 0x12;
		head[9] = 0x00;
		// 下级平台接入码，上级平台给下级平台分配唯一标识码。占4字节
		byte[] MSG_GNSSCENTERID = BytesUtil.int2bytes4(((T809_MessageHeader) message.getMessageHeader()).getGnsscentrid());
		MSG_GNSSCENTERID = BytesUtil.getBigDWord(0, MSG_GNSSCENTERID);
		System.arraycopy(MSG_GNSSCENTERID, 0, head, 10, MSG_GNSSCENTERID.length);
		// 协议版本好标识，上下级平台之间采用的标准协议版编号；长度为3个字节来表示，0x01 0x02 0x0F
		// 标识的版本号是v1.2.15，以此类推。
		byte[] VERSION_FLAG = ((T809_MessageHeader) message.getMessageHeader()).getVersonFlag();
		System.arraycopy(VERSION_FLAG, 0, head, 14, VERSION_FLAG.length);
		// 报文加密标识位b: 0表示报文不加密，1表示报文加密。占1字节
		// byte ENCRYPT_FLAG =
		// ((T809_MessageHeader)message.getMessageHeader()).getEncryptFlag();
		head[17] = 0x00;
		// 数据加密的密匙，长度为4个字节。
		byte[] ENCRYPT_KEY = BytesUtil.int2bytes4(((T809_MessageHeader) message.getMessageHeader()).getEncryptKey());

		System.arraycopy(ENCRYPT_KEY, 0, head, 18, 4);

		byte[] body = new byte[29 + gps.size() * 36];
		// 车牌号
		byte[] vehicle_No = null;
		try {
			vehicle_No = body1203.getVEHICLE_NO().getBytes("GBK");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}

		System.arraycopy(vehicle_No, 0, body, 0, vehicle_No.length);

		byte vehicle_Color = body1203.getVEHICLE_COLOR();

		body[21] = vehicle_Color;

		// byte[] data_Type = BytesUtil.int2bytes2(body9205.getDATA_TYPE());
		body[22] = (byte) 0x12;
		body[23] = 0x03;
		// System.arraycopy(data_Type, 0, body, 22, data_Type.length);

		byte[] data_Length = BytesUtil.int2bytes4(1 + 36 * gps.size());
		data_Length = BytesUtil.getBigDWord(0, data_Length);
		System.arraycopy(data_Length, 0, body, 24, data_Length.length);
		// 对数据头到校验码前的CRC值,占两个字节
		byte gnss_Cnt = BytesUtil.parseIntToByte(gps.size());
		body[28] = gnss_Cnt;

		for (int i = 0; i < gps.size(); i++) {
			String[] params = gps.get(i);
			byte excrypt = 1;
			try {
				excrypt = BytesUtil.parseIntToByte(Integer.parseInt(params[2]));
			} catch (Exception e) {
				excrypt = 2;
			}

			body[29 + i * 36] = excrypt;

			try {
				String day = params[3].substring(0, 2);
				String month = params[3].substring(2, 4);
				String year = params[3].substring(4, 8);
				// 设置年月日

				String hour = params[4].substring(0, 2);
				String minute = params[4].substring(2, 4);
				String second = params[4].substring(4, 6);
				// 设置时分秒
				byte[] date = T809_Util.date2byte(year, month, day);
				System.arraycopy(date, 0, body, 30 + i * 36, date.length);
				// 截取时间
				byte[] time = T809_Util.time2byte(hour, minute, second);
				System.arraycopy(time, 0, body, 34 + i * 36, time.length);

				byte[] lon = BytesUtil.intToByteArray(Integer.parseInt(params[5]));
				System.arraycopy(lon, 0, body, 37 + i * 36, lon.length);
				// 截取纬度
				byte[] lat = BytesUtil.intToByteArray(Integer.parseInt(params[6]));
				System.arraycopy(lat, 0, body, 41 + i * 36, lat.length);

				byte[] vec1 = BytesUtil.int2bytes2(Integer.parseInt(params[7]));
				System.arraycopy(vec1, 0, body, 45 + i * 36, vec1.length);
				// 截取行驶记录速度
				byte[] vec2 = BytesUtil.int2bytes2(Integer.parseInt(params[8]));
				System.arraycopy(vec2, 0, body, 47 + i * 36, vec2.length);

				byte[] vec3 = BytesUtil.intToByteArray(Integer.parseInt(params[9]));
				System.arraycopy(vec3, 0, body, 49 + i * 36, vec3.length);
				// 截取方向
				byte[] direction = BytesUtil.int2bytes2(Integer.parseInt(params[10]));
				System.arraycopy(direction, 0, body, 53 + i * 36, direction.length);

				byte[] altitude = BytesUtil.int2bytes2(Integer.parseInt(params[11]));
				System.arraycopy(altitude, 0, body, 55 + i * 36, altitude.length);
				if(params[12].equals("2147483648"))
				params[12] = "-2147483648";
				// 截取车辆状态
				byte[] state = BytesUtil.intToByteArray(Integer.parseInt(params[12]));
				System.arraycopy(state, 0, body, 57 + i * 36, state.length);
				// 截取报警状态
				if(params[13].equals("2147483648"))
					params[13] = "-2147483648";
				byte[] alarm = BytesUtil.intToByteArray(Integer.parseInt(params[13]));
				System.arraycopy(alarm, 0, body, 61 + i * 36, alarm.length);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] mes = null;
		try {
			bos.write(0x00);
			// 将数据头与数据体写入流中
			bos.write(head);
			bos.write(body);
			bos.write(0x00);
			bos.write(0x00);
			bos.write(0x00);
			// 将数据流转成byte数组
			byte[] bosBytes = bos.toByteArray();
			// 计算crc校验码
			byte[] CRCCode = T809_Util.check(bosBytes);
			bosBytes[bosBytes.length - 3] = CRCCode[0];
			bosBytes[bosBytes.length - 2] = CRCCode[1];
			// 将数据转义
			mes = T809_Util.escapeData(bosBytes);
			mes[0] = 0x5b;
			// 加入数据头与数据尾
			mes[mes.length - 1] = 0x5d;
		} catch (IOException e) {
			log.warn("", e);
		} finally {
			// 如果数据流不为空，关闭流
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					log.warn("", e);
				}
			}
		}

		log.debug("车辆定位信息自动补报请求消息" + BytesUtil.bytesToHexString(mes));
		return mes;
	}

}
